package com.moonbird.springboot.Utils;

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {

    public static void main(String[] args) {
        // 用户可忽略url下载文件部分，可以直接使用本地文件进行相关api调用进行识别
        String exampleWavUrl =
                "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav";
        try {
            InputStream in = new URL(exampleWavUrl).openStream();
            Files.copy(in, Paths.get("asr_example.wav"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            System.out.println("error: " + e);
            System.exit(1);
        }

        // 创建Recognition实例
        Recognition recognizer = new Recognition();
        // 创建RecognitionParam，请在实际使用中替换真实apiKey
        RecognitionParam param =
                RecognitionParam.builder()
                        .model("paraformer-realtime-v2")
                        .format("wav")
                        .sampleRate(16000)
                        .apiKey("sk-c91bee81e9ef4fd4abe43a61b8f38479")
                        .build();

        // 直接将结果保存到script.txt中
        try (FileOutputStream fos = new FileOutputStream("asr_result.txt")) {
            String result = recognizer.call(param, new File("asr_example.wav"));
            JSONObject jsonObject = JSON.parseObject(result);
            String text = jsonObject.getJSONArray("sentences").getJSONObject(0).getString("text");
            System.out.println(text);
            fos.write(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}